﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.Collections.Generic;
using GuavaData;
using System.Reflection;
using System.IO;
using System.Runtime;


namespace GuavaWebServices
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://undone.cs.pdx.edu/")]
   // [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class GuavaControlService : System.Web.Services.WebService
    {
        private string catalog = "guava";
        private string testCatalog = "";
        private static string source = "UNDONE\\SQLEXPRESS";
        private Dictionary<string, XmlDocument> dbChannelMap = new Dictionary<string, XmlDocument>();
        private string path = "";

        [WebMethod]
        public XmlDocument GetGtree()
        {
            return AppData.sendGtree(); 
        }

        [WebMethod]
        public XmlDocument PoseQuery(string squery)
        {
            try
            {
                XDocument doc = null;
                XDocument query = XDocument.Parse(squery);
                XmlDocument docOut = new XmlDocument();
                XmlDocument channel = new XmlDocument();
                channel.Load("C:\\Users\\ekost\\Desktop\\CORIDemo\\guava\\CORIDemo\\bin\\Debug\\channel.xml");
                XDocument c = null;
                using (XmlNodeReader nr = new XmlNodeReader(channel))
                {
                    nr.MoveToContent();
                    c = XDocument.Load(nr);
                }
                try
                {
                    McServer.Init(path, source, catalog, new Channel());
                    doc = McServer.queryDB(query);
                    docOut.Load(doc.CreateReader());
                    return docOut;
                }
                catch (Exception ex)
                {
                    docOut = new XmlDocument();
                    XmlElement xel = docOut.CreateElement("Message");
                    xel.AppendChild(docOut.CreateTextNode(ex.Message+ex.StackTrace.ToString()));
                    docOut.AppendChild(xel);
                    return docOut;
                }


                
            }
            catch (Exception ex)
            {
                Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
                XmlDocument docOut = new XmlDocument();
                XmlElement xel = docOut.CreateElement("Message");
                xel.AppendChild(docOut.CreateTextNode(ex.Message + ex.StackTrace.ToString()));
                docOut.AppendChild(xel);
                return docOut;
            }

        }
       /* [WebMethod]
        public String SetChannel(string oldDB, string newDB, Boolean withData, XmlDocument channel)
        {
           //XmlDocument xDoc = new XmlDocument();
            //xDoc.LoadXml("<xml><Channel>    <Transform type=\"Apply\" table=\"Patient\">      <Function type=\"GuavaData.Function.BitMask\">        <int>6</int>      </Function>      <inCols>        <Other />        <HawaiianPacificIslander />        <Asian />        <AmericanIndian />        <Black />        <White />      </inCols>      <outCols>        <Ethno_Bit_Mask />      </outCols>    </Transform>    <Transform type=\"HMerge\" mergedTable=\"proc_data\" mergedColumn=\"procType\">      <EGD />      <COL />    </Transform>    <Transform type=\"VMerge\" left=\"proc_data\" right=\"SurgicalHistory\" />    <Transform type=\"VSplit\" table=\"proc_data\" new=\"proc_other\">      <Systolic />      <Diastolic />      <EntireExamWNL />      <bilBypass />      <cystRemoval />      <lobectomy />    </Transform>    <Transform type=\"Unpivot\">      <tables>        <proc_data />      </tables>      <attributes>        <item />      </attributes>      <values>        <numericval />      </values>    </Transform>  </Channel> </xml>");
            //channel.LoadXml("<Channel><Transform type=\"Apply\" table=\"codes\">  <Function type=\"GuavaData.Function.ColumnConcatenation\">    <string>3</string>    <string>%s-%s-%s</string>  </Function>  <inCols>    <altlbl />    <prodcode />    <pkgcode />  </inCols>  <outCols>    <altlbl />    <prodcode />    <pkgcode />    <ndc_fda />  </outCols></Transform></Channel>");
            
            this.Server.ScriptTimeout = 10000;
            XDocument c = null;
            using (XmlNodeReader nr = new XmlNodeReader(channel))
            {
                nr.MoveToContent();
                c = XDocument.Load(nr);
            }
            catalog = oldDB;
            testCatalog = newDB;
            try
            {
                ServerData.Init(path, source, catalog, testCatalog, Channel.FromXDocument(c));
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            if (withData)
                ServerData.PushData();
            //dbChannelMap.Add(oldDB + ":" + newDB, channel);
            return "ok";
        }
        [WebMethod]
        public Boolean PushData(string oldDB, string newDB)
        {
            if (catalog == "" || testCatalog == "")
                return false;
            if (oldDB != "" && newDB != "")
                if (oldDB != catalog && newDB != testCatalog)
                {
                    SetChannel(oldDB, newDB, true, dbChannelMap[oldDB + ":" + newDB]);
                    return true;
                }
            ServerData.PushData();
            return true;

        }
        [WebMethod]
        public String EchoXml(XmlElement xml)
        {
            if (xml == null)
            {
                return null;
            }
            else
            {
                XDocument c = null;
                //xml.LoadXml("<Channel><Transform type=\"Apply\" table=\"codes\">  <Function type=\"GuavaData.Function.ColumnConcatenation\">    <string>3</string>    <string>%s-%s-%s</string>  </Function>  <inCols>    <altlbl />    <prodcode />    <pkgcode />  </inCols>  <outCols>    <altlbl />    <prodcode />    <pkgcode />    <ndc_fda />  </outCols></Transform></Channel>");
                using (XmlNodeReader nr = new XmlNodeReader(xml))
                {
                    nr.MoveToContent();
                    c = XDocument.Load(nr);
                }
                //Channel chan = Channel.FromXDocument(c);
                return c.Root.Name.LocalName+" : "+c.Root.Value +" : " + "'" + c.Root.Elements().Reverse().First().Name.ToString() + "'";
            }
        }
        [WebMethod]
        public string Echo(string str)
        {
            if (str == null)
                str = "Error:: I recieved a null string";
            return str;
        }
        [WebMethod]
        public int EchoInt(int i)
        {
            return i;
        }

        [WebMethod]
        public XmlDocument GetChannel()
        {
            if (catalog == "" || testCatalog == "")
                return null;

            XmlNodeReader nr = (XmlNodeReader)ServerData.c.ToXDocument().FirstNode.CreateReader();
            nr.MoveToContent();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(nr);
            return xDoc;


        }*/
    }
}